#include "TextLog.h"
#include "Game.h"
#include "Util.h"

TextLog::TextLog(float height, bool bottomToTop, unsigned int maxLines) {
	m_height = height;
	m_bottomToTop = bottomToTop;
	m_maxLines = maxLines;
	m_currentLine = 0;
}

TextLog::~TextLog() {
	m_lines.clear();
}

void TextLog::save(std::ofstream& file) const {
	int numLines = std::min(50, g_textLog->getNumLines());
	file << numLines << "\n";
	std::list<std::string>::const_iterator iter = m_lines.begin();
	std::advance(iter, numLines-1);
	for(; iter != m_lines.begin(); iter--)
		file << *iter << "\n";
	file << *iter << "\n";
}

void TextLog::load(std::ifstream& file) {
	std::string line;
	std::getline(file, line);
	int numLines = Util::strToInt(line);
	for(int i = 0 ; i < numLines; i++) {
		std::getline(file, line);
		addLine(line);
	}
}

void TextLog::addLine(std::string line) {
	if(line == "") return;
	if(m_lines.size() > m_maxLines)
		m_bottomToTop ? m_lines.pop_back() : m_lines.pop_front();
	m_bottomToTop ? m_lines.push_front(line) : m_lines.push_back(line);
}

std::list<std::string>::const_iterator TextLog::getLine(int i) const {
	std::list<std::string>::const_iterator iter = m_lines.begin();
	std::advance(iter, i);
	return iter;
}

int TextLog::getMaxDrawableLines() const {
	return int(m_height / (g_options.o_fontSize + 1));
}

void TextLog::shift(bool up) {
	if(up) {
		m_currentLine = std::max(0, std::min(int(m_currentLine+1), int(m_lines.size()-getMaxDrawableLines())));
	} else {
		m_currentLine = std::max(int(m_currentLine-1), 0);
	}
}

void TextLog::page(bool up) {
	if(up) {
		m_currentLine = std::max(0, std::min(int(m_currentLine+(getMaxDrawableLines()-1)), int(m_lines.size()-getMaxDrawableLines())));
	} else {
		m_currentLine = std::max(int(m_currentLine-(getMaxDrawableLines()-1)), 0);
	}
}